#include"threadPool.h"
#include"my_header.h"

// 去除字符串末尾的换行符
void remove_newline(char *str) {
    size_t len = strlen(str);
    if (len > 0 && str[len - 1] == '\n') {
        str[len - 1] = '\0';
    }
}

//进入用户的工作目录
//int enter_user_dir(){
//    char cwd[512];//存储目录
//    if(getcwd(cwd,sizeof(cwd))==NULL){
//        DEBUG_PRINT("fail get cwd\n");
//        return -1;
//    }
//    DEBUG_PRINT("current path:%s\n",cwd);
//    //拼接完整路径
//    char user_dir_path[1024];
//    snprintf(user_dir_path,sizeof(user_dir_path),"%s/user_dir",cwd);
//    //进入用户目录
//    if(chdir(user_dir_path)==-1){
//        DEBUG_PRINT("fail to enter user_dir");
//    }
//    return 0;
//
//}


void *threadFunc(void*argc){
    threadPool_t*pthreadPool=(threadPool_t*)argc;
    while(1){
        //加锁
        pthread_mutex_lock(&pthreadPool->mutex);
        while(pthreadPool->taskQueue.queueSize==0&&pthreadPool->exitFlag==0){
            pthread_cond_wait(&pthreadPool->cond,&pthreadPool->mutex);
            DEBUG_PRINT("I am a worker,I am in condtion wait\n");
        }
        //醒来第一件事是看看是否要结束
        if(pthreadPool->exitFlag==1){
            DEBUG_PRINT("I am a worker,I am going to exit\n");
            pthread_mutex_unlock(&pthreadPool->mutex);
            break;
        }
        int netfd=pthreadPool->taskQueue.pFront->netfd;
        //取出netfd后在验证密码
        DEBUG_PRINT("I am a worker,I got a netfd=%d\n",netfd);
        deQueue(&pthreadPool->taskQueue);
        DEBUG_PRINT("I am a worker,I recvice a task,\n");
        pthread_mutex_unlock(&pthreadPool->mutex);
        LOG("worker verdify thepassword");

        //密码验证
        char username[64];
        char password[64];
        int correct=0;
        while(!correct){
            char buf[]="please wirte your name";
            sendMsg(netfd,buf);
            memset(username,0,sizeof(username));
            int sret=recvMsg(netfd,username);
            if(sret==0){
                //对方断开连接
                LOG("Worker disconnect\n");
                DEBUG_PRINT("I am a worker,the client disconnect\n");
                break;
            }
            remove_newline(username);
            // 打印接收到的用户名及其长度
            DEBUG_PRINT("Received username: '%s', length: %zu\n", username, strlen(username));
            DEBUG_PRINT("main  recv username\n");
            LOG("clinet send a username\n");
            memset(password,0,sizeof(password));
            sendMsg(netfd,"please wirte your password");
            sret=recvMsg(netfd,password);
            if(sret==0){
                //对方断开连接
                LOG("Worker disconnect\n");
                DEBUG_PRINT("I am a worker,the client disconnect\n");
                break;
            }
            DEBUG_PRINT("main  recv password\n");
            remove_newline(password);//去除换行符
            DEBUG_PRINT("Received password: '%s', length: %zu\n", password, strlen(password));
            int verify=verify_password(username, password); 
            if (verify== -1) { 
                 DEBUG_PRINT("Server verify fail\n"); 
                 LOG("Username is NOCORRECT!\n"); 
                 sendMsg(netfd,"Username is NOCORRECT!"); 
                 continue; 
             } else if (verify== 1) { 
                 DEBUG_PRINT("Password is CORRECT!\n"); 
                 LOG("Password is CORRECT!\n"); 
                 sendMsg(netfd,"Password is CORRECT!"); 
                 correct=1;
                 break;
             } else { 
                 DEBUG_PRINT("Password is no correct!\n"); 
                 LOG("Password is no correct!\n"); 
                 sendMsg(netfd,"Password is no correct! TRY AGIN\n"); 
                 continue; 
             } 
        }
        if(correct==0){//客户在密码验证阶段断开连接
            break;
        }
        DEBUG_PRINT("worker begian to handle request\n"); 
        //send(netfd,"now you can send your request\n",2,0);
        Canalysis_t cannalysis;
        char request[128];
        // 在进入主循环前，先设置工作目录
        DEBUG_PRINT("before chdir: %s\n", getcwd(NULL, 0));
        //enter_user_dir();
        //DEBUG_PRINT("after chdir: %s\n", getcwd(NULL, 0)); 
        initCanalysis(&cannalysis);//初始化命令结构体u
        while(1){
            bzero(request,sizeof(request));
            bzero(cannalysis.clientCommand,cannalysis.commandLength); 
            getcwd(cannalysis.clientCommand,cannalysis.commandLength);
            int sret=recvMsg(netfd,request);
            if(sret==0){
                //对方断开连接
                LOG("Worker disconnect\n");
                DEBUG_PRINT("I am a worker,the client disconnect\n");
                break;             
            }
            else if (sret == -1) {
                DEBUG_PRINT("recv error: %s\n", strerror(errno));
                continue;
            } else if (strlen(request) == 0) {
                //防止客户端一直发送空包过来，例如sizeof(4096)
                LOG("client send empty data");
                DEBUG_PRINT("Received empty data, closing connection\n");
                break;  // 主动断开连接
            }
            remove_newline(request);//去除换行符
            DEBUG_PRINT("Received request: '%s', length: %zu\n", request, strlen(request));
            LOG("client send a command");
            DEBUG_PRINT("current path: %s\n", getcwd(NULL, 0)); 
            sret=separationCommand(request, &cannalysis);
            DEBUG_PRINT("current path: %s\n", getcwd(NULL, 0));
//            if(sret!=0){
//                send(netfd,"your request is wrong!\n",28,0);
//                continue;
//            }
            //对命令要求进行操作
            sret=cannalysis.flag;
            if(sret==-1){
                sendMsg(netfd,cannalysis.clientCommand);
                LOG(cannalysis.clientCommand);
            }
            if(sret>=1&&sret<=5){
                //发字符串
                LOG("The client request directory information");
                DEBUG_PRINT("worker recv a request for directory information\n");
                DEBUG_PRINT("return clientCommand=%s\n",cannalysis.clientCommand);
                sendMsg(netfd,cannalysis.clientCommand);
            }else if(sret==6){
                LOG("The client request download a file");
                DEBUG_PRINT("worker recv a request for dowload a file\n");
                DEBUG_PRINT("filename=%s\n",cannalysis.lastname);
                //发文件
                DEBUG_PRINT("current path: %s\n", getcwd(NULL, 0));
                sret=sendFile(netfd,cannalysis.lastname);
                if(sret!=0){
                    DEBUG_PRINT("transfile fail\n");
                    continue;
                }
                DEBUG_PRINT("transfile success\n");
                sendMsg(netfd,"download success");
            }else if(sret==7){
                //收文件
                LOG("The client request save a file");
                DEBUG_PRINT("worker recv a request for save file\n");
                DEBUG_PRINT("filename=%s\n",cannalysis.lastname);
                sret=recvFile(netfd);
                if(sret!=0){
                    DEBUG_PRINT("recvfile fail\n");
                    continue;
                }
                DEBUG_PRINT("transfile success\n");
                sendMsg(netfd,"puts success");
            }else if(sret==8){
                LOG("The client request remove a file");
                DEBUG_PRINT("The client request remove a file\n");
                sendMsg(netfd,"download success");
            }
            if(DEBUG_MODE){//在调试的时候让程序慢点运行
                sleep(3);
            }

        }
        freeCanalysis(&cannalysis);
        close(netfd);
    }
}


int makeWorker(threadPool_t*pthreadPool){
    for(int i=0;i<pthreadPool->tidArr.workerNum;++i){
        pthread_create(&pthreadPool->tidArr.arr[i],NULL,threadFunc,pthreadPool);
    }
    return 0;
}
